
class TeacherController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    def createBlogService
    def authenticateService
    def timeUtilService
    def teacherSearcheService
    
    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        def teacherstaff = org.grails.plugins.lookups.Lookup.codeList("teacherstaff")
        def teacherdegree = org.grails.plugins.lookups.Lookup.codeList("teacherdegree")
        def teacherfeatures = org.grails.plugins.lookups.Lookup.codeList("teacherfeatures")

        List roles = Role.list()
        def adminRole = authenticateService.securityConfig.security.adminRole
        def schoolMasterRole = authenticateService.securityConfig.security.schoolMasterRole
        def grepRoles = roles.grep{
            it.authority != adminRole && it.authority != schoolMasterRole
        }
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [teacherInstanceList: session.school?Teacher.findAllBySchool(session.school) : Teacher.list(sort: 'school'),
        teacherInstanceTotal: session.school?Teacher.countBySchool(session.school) : Teacher.count(),
        teacherstaff:teacherstaff,
        teacherdegree:teacherdegree,
        teacherfeatures:teacherfeatures,
        roles:grepRoles]
    }

    def create = {
        def teacherInstance = new Teacher()
        teacherInstance.properties = params
        return [teacherInstance: teacherInstance]
    }

	private saveRole(def person) {  
		def config = authenticateService.securityConfig
		def teacherRole = config.security.teacherRole
		def role = Role.findByAuthority(teacherRole)
		role.addToPeople(person) 
	}

    def save = {

           
        // 由于前台用了jquery的日期插件，这里需要转换日期的格式
        Date birthday = timeUtilService.stringToDate(params.birthday)
        log.info(birthday)
        params.birthday = birthday

        def teacherInstance = new Teacher(params)       

        if(Teacher.countByUsernameAndSchool(params.username+"-${session.school.id}",session.school) > 0){
            teacherInstance.errors.rejectValue('username', '此用户名已经被使用')
            return render(view: "create", model: [teacherInstance: teacherInstance])
        } 


        if(params.state == null || params.state == ""){
            teacherInstance.source = ''
            teacherInstance.enabled = true;
        }else{
            teacherInstance.source = params.source
            teacherInstance.enabled = false 
        }
        teacherInstance.passwd = authenticateService.encodePassword(grailsApplication.config.grails.default.teacher.passwd)
        if(session.school){
            teacherInstance.school = session.school
        }
        teacherInstance.username = teacherInstance.username+grailsApplication.config.grails.default.username.segment+teacherInstance.school.id
        log.info(teacherInstance.username)

        
        
        if (teacherInstance.save(flush: true)) {
            // 让新添加的教师的角色为没有，强制让校长或者主任去为教师专门设置角色
//            saveRole(teacherInstance)
            if(createBlogService.sendCreateBlog(teacherInstance,grailsApplication.config.grails.default.blog.create.uri)){
                teacherInstance.hasBlog = true
                teacherInstance.save(flush:true)
                flash.message = "创建教师${teacherInstance.name}成功，同时建立了教师博客！"
            }else{
                flash.message = "创建教师${teacherInstance.name}成功，创建教师博客失败，请在教师列表中再次进行创建，如果依然有错误，请联系管理员！"
            }
            redirect(action: "list")
        }else {
            render(view: "create", model: [teacherInstance: teacherInstance])
        }
    }

    def show = {
        def teacherInstance = Teacher.get(params.id)
        if (!teacherInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'teacher.label', default: 'Teacher'), params.id])}"
            if(!params.searchFlag){
                redirect(action: "list")
            }else{
                redirect(action: "teacherSearchList",controller:"teacherMgr")
            }
        }
        else {
            [teacherInstance: teacherInstance]
        }
    }

    def edit = {
        def teacherInstance = Teacher.get(params.id)
        if (!teacherInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'teacher.label', default: 'Teacher'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [teacherInstance: teacherInstance]
        }
    }

    def update = {        
        def teacherInstance = Teacher.get(params.id)
        if (teacherInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (teacherInstance.version > version) {
                    
                    teacherInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'teacher.label', default: 'Teacher')] as Object[], "Another user has updated this Teacher while you were editing")
                    render(view: "edit", model: [teacherInstance: teacherInstance])
                    return
                }
            }

            // 由于前台用了jquery的日期插件，这里需要转换日期的格式
            Date birthday = timeUtilService.stringToDate(params.birthday)
            log.info(birthday)
            params.birthday = birthday
            teacherInstance.properties = params
            if(params.state == null || params.state == ""){
                teacherInstance.source = ''
                teacherInstance.enabled = true;
            }else{
                teacherInstance.source = params.source
            }
            if (!teacherInstance.hasErrors() && teacherInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'teacher.label', default: 'Teacher'), teacherInstance])}"
                if(!params.searchFlag){
                    redirect(action: "list")
                }else{
                    redirect(action: "teacherSearchList",controller:"teacherMgr")
                }
            }
            else {
                render(view: "edit", model: [teacherInstance: teacherInstance,params:params])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'teacher.label', default: 'Teacher'), params.id])}"
            if(!params.searchFlag){
                redirect(action: "list")
            }else{
                redirect(action: "teacherSearchList",controller:"teacherMgr")
            }
        }
    }

    def delete = {
//        def teacherInstance = Teacher.get(params.id)
//        if (teacherInstance) {
//            try {
//                teacherInstance.organize.toList().each { it.removeFromTeachers(teacherInstance) }
//                teacherInstance.course.clear()
//                teacherInstance.delete(flush: true)
//                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'teacher.label', default: 'Teacher'), params.id])}"
//                redirect(action: "list")
//            }
//            catch (org.springframework.dao.DataIntegrityViolationException e) {
//                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'teacher.label', default: 'Teacher'), params.id])}"
//                redirect(action: "show", id: params.id)
//            }
//        }
//        else {
//            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'teacher.label', default: 'Teacher'), params.id])}"
//            redirect(action: "list")
//        }
    }
}
